import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, Tooltip, Select, Tree, Icon as AIcon,
} from 'antd';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import { boundingExtent, getCenter } from 'ol/extent';
import { Vector } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import Feature from 'ol/Feature';
import { Icon, Stroke, Text, Style, Fill } from 'ol/style';
import Point from 'ol/geom/Point';
import { fromLonLat, toLonLat } from 'ol/proj';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem, getFileType } from '@/utils/utils';
import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEditArea from '../Owner/AddOrEditArea';
import Owner from './owner';
import yali from '../../images/cun.png';
import yali_blue from '../../images/yali_blue.png';
import yali_warm from '../../images/yali_red.gif';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;
const { TreeNode, DirectoryTree } = Tree;
const RadioButton = Radio.Button;
const ButtonGroup = Button.Group;

const RadioGroup = Radio.Group;

@connect(({ area_manage, loading, global }) => ({
  area_manage,
  global,
  loading: loading.models.area_manage,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.pointerLayer = null;
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      point:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      area_manage: { pageLoaded, scrollData, pointerLayer },
    } = this.props;
    this.pointerLayer = pointerLayer;
    console.log('pageLoaded', pageLoaded);
    const that = this;
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      that.renderMap();

    } else {
      const {
        area_manage: { searchParams },
      } = that.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'area_manage/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = that.props;
          dispatch({
            type: 'area_manage/changeLoaded',
          });
          dispatch({
            type: 'area_manage/changeTableY',
            callback: function() {
              that.renderMap();
            },
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    // table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'area_manage/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'area_manage/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    // table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'area_manage/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      area_manage: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label="文章标题">
          {getFieldDecorator('title', {
            initialValue: searchParams.title,
          })(<Input style={{ width: '180px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  type: searchParams.type,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            find(this.permissions, { name: 'article_edit' }) &&
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              发布文章
            </Button>
          }

        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'area_manage/add',
      payload: {
        ...formValues,
        parent_id: formValues.parent_id ? formValues.parent_id.split('$')[0] : '',
      },
      callback() {
        message.success('添加区域成功');
        that.setState({
          addModal: false,
        });
        const {
          area_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    const {
      area_manage: { searchParams },
    } = this.props;
    this.handleSearch({
      status: '0',
      title: '',
      page: 1,
      per_page: 30,
      type: searchParams.type,
    });
  };

  handleEdit = () => {
    console.log('handleEdit')
    const formValues = this.EditForm.props.form.getFieldsValue();
    const { dispatch, area_manage: {  selectedObj } } = this.props;
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `area_manage/edit`,
      payload: {
        ...selectedObj,
        ...formValues,
        id: this.state.editRecord.id,
        parent_id: formValues.parent_id ? formValues.parent_id.split('$')[0] : '',
      },
      callback() {
        message.success('修改区域成功');
        that.setState({
          editModal: false,
          editRecord: { ...that.state.editRecord, ...formValues },
        });
        const {
          area_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleEditLatLog = () => {
    const that=this;
    const { dispatch, area_manage: {  selectedObj } } = that.props;
    console.log(this.state.point)

    this.props.dispatch({
      type: `area_manage/edit`,
      payload: {
        ...selectedObj,
        longitude:this.state.point[0],
        latitude:this.state.point[1],
      },
      callback() {
        message.success('保存修改成功');
        const {
          area_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `area_manage/remove`,
      payload: { id },
      callback: () => {
        message.success('删除区域成功');
        const {
          area_manage: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={`${item.name} (${item.account_count}水表)`} key={item.id} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={`${item.name} (${item.account_count}水表)`} {...item} isLeaf={item.children.length === 0}/>;
    });
  renderMap = () => {
    const that = this;
    const { dispatch, area_manage: { layers, zoom, center, selectedKeys } } = this.props;
    let map = this.map = new Map({
      target: 'mapDiv2',
      layers: [...layers],
      view: new View({
        center: fromLonLat(center),//经纬度
        zoom: zoom,
        maxZoom: 18.5,
      }),
    });
    console.log('renderMap');
    map.on('moveend', function(e) {
      let zoom = map.getView().getZoom();  //获取当前地图的缩放级别
      let center = map.getView().getCenter();
      console.log(toLonLat(center));
      console.log(zoom);
      dispatch({
        type: 'area_manage/changeOneState',
        payload: {
          zoom, center: toLonLat(center),
        },
      });
    });
    console.log(that.pointerLayer)
    if (that.pointerLayer&& selectedKeys[0] !== 'all') {
      map.addLayer(that.pointerLayer);
    }else{
      console.log('渲染全部')
      that.renderAllPoint()
    }
    map.on('click', function(e) {
      const { dispatch, area_manage: { selectedKeys, selectedObj } } = that.props;
      //在点击时获取像素区域;
      console.log('selectedKeys', selectedKeys);
      if (selectedKeys.length > 0 && selectedKeys[0] !== 'all') {
        that.setState({
          point: toLonLat(e.coordinate),
        });
        if (that.pointerLayer) {
          map.removeLayer(that.pointerLayer);
        }
        let mockvectorSource = that.createApoint(e.coordinate, selectedObj);
        // 创建标注图层
        that.pointerLayer = new Vector({
          zIndex: 12,
          source: mockvectorSource,
        });
        // 将标注图层添加到地图上
        map.addLayer(that.pointerLayer);
        that.props.dispatch({
          type: 'area_manage/changeOneState',
          payload: {
            hadChanged: true,
            pointerLayer: that.pointerLayer,
          },
          callback: () => {
          },
        });
      }

      var feature = map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
        return feature;
      });
      if (feature) {
        console.log('feature', feature)
        that.setState({
          editRecord:feature.get('dataset'),
          infoModal:true
        })
      }

    });
  };
  renderOnePoint=(pointeData)=>{
    const that=this
    const { dispatch, area_manage: { selectedObj } } = that.props;
    let mockvectorSource = that.createApoint(fromLonLat([pointeData.longitude, pointeData.latitude]), selectedObj);
    // 创建标注图层
    that.pointerLayer = new Vector({
      source: mockvectorSource,
    });
    // 将标注图层添加到地图上
    that.map.addLayer(that.pointerLayer);

    let Coordinates = [];
    Coordinates.push(fromLonLat([pointeData.longitude, pointeData.latitude]));
    let view = this.map.getView();
    let extent = boundingExtent(Coordinates);
    let center = getCenter(extent);   //获取边界区域的中心位置
    view.setCenter(center);  //设置当前地图的显示中心位置
  }
  renderAllPoint = () => {
    const { dispatch, area_manage: { pointeData } } = this.props;
    //绘制点
    if (this.pointerLayer) {
      this.map.removeLayer(this.pointerLayer);
    }
    let Coordinates = [];
    let pressFeature = [];
    for (let i = 0; i < pointeData.length; i++) {
      if(pointeData[i].longitude){
        let point = this.setPoint(fromLonLat([pointeData[i].longitude, pointeData[i].latitude]), pointeData[i]);
        pressFeature.push(point);
        Coordinates.push(fromLonLat([pointeData[i].longitude, pointeData[i].latitude]));
      }
    }
    console.log('pressFeature',pressFeature)
    if(pressFeature.length===0){
      return false
    }
    let view = this.map.getView();
    let extent = boundingExtent(Coordinates);
    let center = getCenter(extent);   //获取边界区域的中心位置
    view.setZoom(12);
    view.setCenter(center);  //设置当前地图的显示中心位置
    this.pressSource = new VectorSource({
      features: pressFeature,
    });
    this.pointerLayer = new Vector({
      source: this.pressSource,
    });
    this.map.addLayer(this.pointerLayer);
  };
  setPoint = (coordinate, selectedObj) => {
    const that = this;
    let point = new Feature({
      geometry: new Point(coordinate),
      name: '压力传感器',
      dataset:selectedObj
    });
    //设置图标的样式
    point.setStyle(new Style({
      /**{olx.style.IconOptions}类型*/
      image: new Icon({
        anchorOrigin: 'top-right',
        offsetOrigin: 'top-right',
        src: yali,
      }),
      text: new Text({
        //位置
        textAlign: 'center',
        //基准线
        textBaseline: 'middle',
        //文字样式
        font: 'normal 14px 微软雅黑',
        offsetY: 22,
        //文本内容
        text: selectedObj.name ? selectedObj.name + ' : '+ selectedObj.account_count+' 水表'  : '',
        //文本填充样式（即文字颜色）
        fill: new Fill({ color: '#ffffff' }),
        backgroundFill: new Fill({ color: '#0068cd' }),
        padding: [3, 0, 0, 3],
      }),
    }));
    return point;
  };
  createApoint = (coordinate, selectedObj) => {
    const that = this;
    let point = new Feature({
      geometry: new Point(coordinate),
      name: '压力传感器',
      dataset:selectedObj
    });
    //设置图标的样式
    point.setStyle(new Style({
      /**{olx.style.IconOptions}类型*/
      image: new Icon({
        anchorOrigin: 'top-right',
        offsetOrigin: 'top-right',
        src: yali,
      }),
      text: new Text({
        //位置
        textAlign: 'center',
        //基准线
        textBaseline: 'middle',
        //文字样式
        font: 'normal 14px 微软雅黑',
        offsetY: 22,
        //文本内容
        text: selectedObj.name ? selectedObj.name + ' : '+ selectedObj.account_count+' 水表'  : '',
        //文本填充样式（即文字颜色）
        fill: new Fill({ color: '#ffffff' }),
        backgroundFill: new Fill({ color: '#0068cd' }),
        padding: [3, 0, 0, 3],
      }),
    }));

    // 创建标注的数据源
    let mockvectorSource = new VectorSource({
      features: [point],
    });
    return mockvectorSource;
  };

  render() {
    const that = this;
    const {
      area_manage: { data, loading, tableY, selectedObj, hadChanged, selectedKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>区域管理</span>
      </div>
      <div className="table-page">
        <div className={'table-data-content'} style={{ display: 'flex' }}>
          <div
            style={{ width: '215px', height: tableY, overflowY: 'auto', background: '#eeeeee'}}>
            <div style={{ display: 'flex', justifyContent: 'space-evenly', marginTop: '10px' }}>
              <Tooltip title={'添加区域'}>
                <Button shape="circle" type="primary" icon={'plus-circle'} onClick={() => {
                  this.setState({
                    addModal: true,
                  });
                }}></Button>
              </Tooltip>
              <Tooltip title={'修改区域'}>
                <Button shape="circle" type="primary" disabled={selectedKeys.length === 0 ||selectedKeys[0]==='all'} icon={'edit'}
                        onClick={() => {
                          this.setState({
                            editModal: true,
                          });
                        }}
                ></Button>
              </Tooltip>
         {/*     <Tooltip title={'删除区域'}>
                <Button onClick={(e) => {
                  const that = this;
                  confirm({
                    title: `确定要删除"${selectedObj.name}"吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered: true,
                    maskClosable: true,
                    onOk() {
                      that.handleDelete(selectedObj.id);
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }
                } shape="circle" type="danger" disabled={selectedKeys.length === 0} icon={'delete'}></Button>
              </Tooltip>*/}
            </div>
            {
              data.length > 0 &&
              <DirectoryTree className={'tree'} style={{ marginTop: '10px' }} defaultExpandAll
                             selectedKeys={selectedKeys}
                             expandAction={'doubleClick'}
                             onSelect={(keys, event) => {
                               console.log('Trigger Select', keys);
                               console.log('Trigger event', event.node.props.dataRef);
                               if (hadChanged) {
                                 console.log('已经编辑过');
                                 confirm({
                                   title: `切换区域后，当前修改位置不会保存`,
                                   content: '确定要切换吗？',
                                   okText: '确定',
                                   okType: 'primary',
                                   cancelText: '取消',
                                   centered: true,
                                   maskClosable: true,
                                   onOk() {
                                     that.setState({
                                       editRecord: event.node.props.dataRef ? event.node.props.dataRef : {},
                                     });
                                     if (that.pointerLayer) {
                                       that.map.removeLayer(that.pointerLayer);
                                     }
                                     if(keys[0]==='all'){
                                       console.log('渲染全部点')
                                       that.renderAllPoint()
                                     }
                                     that.props.dispatch({
                                       type: 'area_manage/changeOneState',
                                       payload: {
                                         selectedKeys: keys,
                                         selectedObj: event.node.props.dataRef ? event.node.props.dataRef : {},
                                         hadChanged: false,
                                       },
                                       callback: () => {
                                         if(event.node.props.dataRef&&event.node.props.dataRef.latitude){
                                           that.renderOnePoint(event.node.props.dataRef)
                                         }
                                       },
                                     });
                                     // that.handleDelete(event.row.id);
                                   },
                                   onCancel() {
                                   },
                                 });
                                 return false;
                               }
                               that.setState({
                                 editRecord: event.node.props.dataRef ? event.node.props.dataRef : {},
                               });
                               if (that.pointerLayer) {
                                 that.map.removeLayer(that.pointerLayer);
                               }
                               if(keys[0]==='all'){
                                 console.log('渲染全部点')
                                 that.renderAllPoint()
                               }
                               that.props.dispatch({
                                 type: 'area_manage/changeOneState',
                                 payload: {
                                   selectedKeys: keys,
                                   selectedObj: event.node.props.dataRef ? event.node.props.dataRef : {},
                                 },
                                 callback: () => {
                                   if(event.node.props.dataRef&&event.node.props.dataRef.latitude){
                                     that.renderOnePoint(event.node.props.dataRef)
                                   }
                                 },
                               });
                             }} onExpand={(expandedKeys) => {
              }}>
                <TreeNode icon={<AIcon type="home"/>} title="全部地区" key="all" isLeaf/>
                {this.renderTreeNodes(data)}
              </DirectoryTree>
            }
          </div>
          <div style={{ height: tableY, flex: '1', background: '#000', position: 'relative' }}>
            <div id={'mapDiv2'} style={{
              display: 'flex',
              height: '100%',
              flexDirection: 'column',
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            </div>
            {
              hadChanged &&
              <div style={{ position: 'absolute', left: '47%', bottom: '20px' }}>
                <Button size={'large'} type={'danger'} onClick={() => {
                  if(this.state.point.length===0){
                    return false
                  }
                  that.handleEditLatLog()
                  that.props.dispatch({
                    type: 'area_manage/changeOneState',
                    payload: {
                      hadChanged: false,
                    },
                    callback: () => {
                    },
                  });
                }}>保存修改</Button>
              </div>}
          </div>
        </div>


      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加区域"/>}
        visible={this.state.addModal}
        centered
        onOk={this.handleAdd}
        className="addModal"
        onCancel={() => {
          this.setState({ addModal: false });
        }}

      >
        <AddOrEditArea data={data} wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 : ${selectedObj.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditArea
          data={data}
          editRecord={selectedObj}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
      <Drawer
        title={`${this.state.editRecord.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={855}
        visible={this.state.infoModal}
      >
        <Owner editRecord={this.state.editRecord}/>
      </Drawer>
    </div>;
  }
}

export default BasicList;
